How to get the first word in a string Python

get the first word in a string Python

Sometimes we come across situations where we need to get first word in string python. Hence it is often helpful to have shorthands to perform this function. This article also covers the situations where we need all words present in the string.

Method #1: Using split()

Using the split function, we can break the string into a list of words. Use str.split() and list indexing to get the first word in a string. Call str.split() to create a list of all words in str separated by space or newline character. Index the result of str.split() with [0] to return the first word in str.

Get first word in string Python

Getting the first word in a string will return the first series of characters that precede a space or a newline character. For example, getting the first word in the “Tutorials Website” string returns “Tutorials.”

Output:

Get first word in string python

Get the All words in a string

Getting all words in a string will return the series of characters that precede a space or a newline character. For example,

Output:

get first word in string python

Read Also: Python vs Node.JS: Which one is the best fit for your project?

Conclusion:

Using the Split function to Get first word in string python is the most generic and recommended method to perform this particular task. But the drawback is that it fails to contain punctuation marks in string cases.

Hire Best Website Designer and Developerin Delhi India

Related posts